import { getBlockchainRecords, addBlockchainRecord } from '@/api/blockchain'

const state = {
  records: []
}

const mutations = {
  setRecords(state, records) {
    state.records = records
  },
  addRecord(state, record) {
    state.records.push(record)
  }
}

const actions = {
  async fetchRecords({ commit }) {
    try {
      const response = await getBlockchainRecords()
      commit('setRecords', response.data)
      return response
    } catch (error) {
      throw error
    }
  },
  async addRecord({ commit }, payload) {
    try {
      const response = await addBlockchainRecord(payload)
      commit('addRecord', response.data)
      return response
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  allRecords(state) {
    return state.records
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
